from queue import Queue


def find_maze(maze):
    if maze == [] or maze[0] == []:
        return -1

    n = len(maze)
    m = len(maze[0])

    dist = [[-1 for _ in range(m)] for _ in range(n)]

    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    first = [0, 0]
    dist[first[0]][first[1]] = 0
    my_queue = Queue()
    my_queue.put(first)

    while not my_queue.empty():
        node = my_queue.get()
        i, j = node
        for di, dj in directions:
            nexti = i + di
            nextj = j + dj
            if 0 <= nexti < n and 0 <= nextj < m:
                if maze[nexti][nextj] == 0 and dist[nexti][nextj] == -1:
                    dist[nexti][nextj] = dist[i][j] + 1
                    my_queue.put([nexti, nextj])

    print(dist[n - 1][m - 1])


if __name__ == "__main__":
    maze = [
        [0, 1, 0, 0, 0],
        [0, 1, 0, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 0, 0, 1, 0],
    ]
    find_maze(maze)
